package com.bootdo.wordbar.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bootdo.wordbar.domain.WordbarDO;
import com.bootdo.wordbar.service.WordbarService;
import com.bootdo.APP2;
import com.bootdo.check.domain.VideoDO;
import com.bootdo.common.utils.ExcelUtils;
import com.bootdo.common.utils.FileUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.download.controller.StaticSet;

/**
 * 词条任务表
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2018-08-07 11:10:37
 */
 
@Controller
@RequestMapping("/wordbar/wordbar")
public class WordbarController {
	@Autowired
	private WordbarService wordbarService;
	
    @Value("${excelFile}")
    private String filePath;
	
    @Value("${logoUrl}")
    private String logourl; 
	
    @Value("${baikeUrl}")
    private String baikeurl;
    
	@GetMapping()
	@RequiresPermissions("wordbar:wordbar:wordbar")
	String Wordbar(){
	    return "wordbar/wordbar/wordbar";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("wordbar:wordbar:wordbar")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<WordbarDO> wordbarList = wordbarService.list(query);
		int total = wordbarService.count2(query);
		PageUtils pageUtils = new PageUtils(wordbarList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("wordbar:wordbar:add")
	String add(){
	    return "wordbar/wordbar/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wordbar:wordbar:edit")
	String edit(@PathVariable("id") Integer id,Model model){
		WordbarDO wordbar = wordbarService.get(id);
		model.addAttribute("wordbar", wordbar);
	    return "wordbar/wordbar/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wordbar:wordbar:add")
	public R save(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String fileName = file.getOriginalFilename();
        boolean uploadSuccess = false;
        try {
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
            uploadSuccess = true;
        } catch (Exception e) {
            return R.error();
        }
        if (uploadSuccess == true) {
            String sheetName;
            Map<String, List<List<String>>> excelContent = ExcelUtils.read(filePath + fileName);
            for (Map.Entry<String, List<List<String>>> sheetContent : excelContent.entrySet()) {
                sheetName = sheetContent.getKey();
                for (List<String> v : sheetContent.getValue()) {
                	 WordbarDO wordbar = new WordbarDO();
                	 
                	 wordbar.setWord(v.get(1));
                	 wordbar.setUrl(v.get(2));
                	 wordbar.setStatue("待下发任务");
                	 wordbar.setFielname(fileName);
                	 wordbar.setSheetname(sheetName);
                	 wordbarService.save(wordbar);
                }
            }
        }
        return R.ok();
    }
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wordbar:wordbar:edit")
	public R update( WordbarDO wordbar){
		wordbarService.update(wordbar);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wordbar:wordbar:remove")
	public R remove( Integer id){
		if(wordbarService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wordbar:wordbar:batchRemove")
	public R remove(@RequestParam("ids[]") Integer[] ids){
		wordbarService.batchRemove(ids);
		return R.ok();
	}
	

	/**
	 * 清空表
	 */
	@PostMapping( "/allRemove")
	@ResponseBody
	@RequiresPermissions("wordbar:wordbar:remove")
	public R allRemove(){
		wordbarService.clear();
		return R.ok();
	}
	
	
	
	
	@PostConstruct
	public void doCheck() {

      
		Thread thread = new Thread(() -> {
			// 读取列表数据进行判断
			

		Map<String, Object> params = new LinkedHashMap<String, Object>() ;	
		params.put("limit", 1000);
		params.put("offset", 0);
		params.put("statue", "待下发任务");

		while(true) {
		    Query query = new Query(params);
	
		    
			List<WordbarDO> wordbarList = wordbarService.list(query);
			
		    for (WordbarDO wordbarDO : wordbarList) {
		    	
		    	String url = wordbarDO.getUrl();
		    	//java.net.URLEncoder.encode("中文","utf-8")
		        
		        
		        if (wordbarDO.getUrl()== null || wordbarDO.getUrl().isEmpty()) {
		        	try {
						url =  baikeurl + URLEncoder.encode(wordbarDO.getWord(),"utf-8").replace("+", " ");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		        }
		      
		        System.out.println(url);
		
		        try {	
		    		
		    	Document doc =Jsoup.connect(url)//请求参数
		    				.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36") //设置User-Agent
		    				.timeout(10000) //设置连接超时时间
		    				.get();
		    		
		    	Element sh = doc.select("div.pro-content-title").first();//("");
		    	Element logo = doc.select("div.professional-header").first();
		    	Boolean fg = true;
		    	String res = "";
		   
		    	
		    	if (sh==null) {		    		
		    		 fg = false;
		    	   	 res += "没有审核模块";
		    	} else if (sh.text().contains("审核")) {
		    		 res += "包含审核信息："+sh.text();
		    	} else {
		    		 res += "没有审核字样";
		    		fg = false;
		    	}
		    	
		        if (logo==null) {
		        	 fg = false;
		    	   	 res += "没有logo模块";
		        } else if (logo.html().contains(logourl)) {
		        	res += " 包含logo信息："+logo.text();
		        } else {
		    		res += "没有logo出现，或启用了新的logo地址";
		    		fg = false;
		        }
		        
		        if (fg) {
		        	wordbarDO.setStatue("审查合格");
		        	wordbarDO.setChekcResult(res);
		        } else {
		        	wordbarDO.setStatue("审查不合格");
		        	wordbarDO.setChekcResult(res);
		        }
		    
				
				try {
				Element time =doc.select("span.j-modified-time").first();
				wordbarDO.setNuma(time.text());
				}catch (Exception e) {
					e.printStackTrace();
				}

				wordbarDO.setUrl(url);
//				System.out.println(wordbarDO.getStatue());
//				System.out.println(wordbarDO.getChekcResult());
		    	wordbarService.update(wordbarDO);
//		        if (wordbarDO.getStatue().equals("审查不合格")) {
//			    	try {
//						Thread.sleep(10000);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//			        }
		    	
				} catch (Exception e) {
					// TODO Auto-generated catch block
					wordbarDO.setStatue("审查不合格");
					wordbarDO.setUrl(url);
			    	wordbarDO.setChekcResult("链接失效或网络问题,请重新确认");
			    	wordbarService.update(wordbarDO);
					e.printStackTrace();
				}
		
			}
		    
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		});
		thread.setDaemon(true);
		thread.start();

	}

	
}
